﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Entities;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.Forecasts.Add;

public class AddForecastsCommandHandler : IRequestHandler<AddForecastsCommandRequest, AddForecastsCommandResponse>
{
    private readonly IForecastRepository _forecastRepository;
    private readonly IMapper _mapper;
    private readonly IRegionRepository _regionRepository;

    public AddForecastsCommandHandler(IMapper mapper, IForecastRepository forecastRepository, IRegionRepository regionRepository)
    {
        _mapper = mapper;
        _forecastRepository = forecastRepository;
        _regionRepository = regionRepository;
    }

    public async Task<AddForecastsCommandResponse> Handle(AddForecastsCommandRequest request, CancellationToken cancellationToken)
    {
        var regionExists = await _regionRepository.AnyAsync(x => x.Id == request.RegionId, cancellationToken);
        if (regionExists == false) throw new NotFoundException($"Регион с id '{request.RegionId}' не найден");

        var newForecast = new Forecast();
        newForecast.RegionId = request.RegionId;
        newForecast.Datetime = request.DateTime.ToUniversalTime();
        newForecast.Temperature = request.Temperature;
        newForecast.WeatherCondition = request.WeatherCondition;

        await _forecastRepository.InsertAsync(newForecast, cancellationToken);
        return _mapper.Map<AddForecastsCommandResponse>(newForecast);
    }
}